const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');

const SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7";
const ALGORITHM = "HS256";
const ACCESS_TOKEN_EXPIRE_MINUTES = 30;

// 生成JWT Token
function createAccessToken(data) {
    const expiresIn = ACCESS_TOKEN_EXPIRE_MINUTES * 60; // 转换为秒
    return jwt.sign(data, SECRET_KEY, { expiresIn, algorithm: ALGORITHM });
}

// 验证JWT Token
function verifyAccessToken(token) {
    try {
        return jwt.verify(token, SECRET_KEY);
    } catch (error) {
        return null;
    }
}

// 模拟用户数据和密码
const userData = {
    username: 'testuser',
    password: 'password123'
};

// 哈希密码
async function hashPassword(password) {
    const saltRounds = 10;
    return await bcrypt.hash(password, saltRounds);
}

// 示例：生成和验证Token
(async () => {
    // 哈希用户密码
    const hashedPassword = await hashPassword(userData.password);
    console.log(`Hashed Password: ${hashedPassword}`);

    // 生成Token
    const tokenData = { sub: userData.username };
    const accessToken = createAccessToken(tokenData);
    console.log(`Generated Access Token: ${accessToken}`);

    // 验证Token
    const verifiedPayload = verifyAccessToken(accessToken);
    if (verifiedPayload) {
        console.log("Token is valid. Payload:", verifiedPayload);
    } else {
        console.log("Token is invalid or expired.");
    }
})();
